package com.kevin.v2.spring.formework.aop.proxy;

import com.kevin.v2.spring.formework.aop.intercept.KvMethodInvocation;
import com.kevin.v2.spring.formework.aop.support.KvAdviseSupport;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

public class KvCglibAopProxy implements KvAopProxy,MethodInterceptor {

   private KvAdviseSupport support;

   public KvCglibAopProxy (KvAdviseSupport support) {
      this.support = support;
   }

   @Override
   public Object getProxy () {
      return getProxy(support.getTargetClass().getClassLoader());
   }

   @Override
   public Object getProxy (ClassLoader classLoader) {
      Enhancer enhancer = new Enhancer();
      enhancer.setSuperclass(support.getTargetClass());
      enhancer.setCallback(this);
      return enhancer.create();


   }

   @Override
   public Object intercept (Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
      List<Object> interceptorAndDynamicMethodMatcher =
              support.getInterceptorAndJdkInterceptionAdvice(method, support.getTargetClass());
      KvMethodInvocation im = new KvMethodInvocation( support, method,
              support.getTarget(), support.getTargetClass(),args, interceptorAndDynamicMethodMatcher);

      return im.proceed();
   }
}
